package org.example.main.multi_threading;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Author: WangShengJie
 * @Date: 2025/6/1
 */
public class CreateMoreThreadMethodDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 继承Thread类，重写run()方法
         * 不支持线程池
         * 适用场景：简单线程任务
         */
        System.out.println("当前线程：" + Thread.currentThread());
        Thread extendsThread = new Thread() {
            @Override
            public void run() {
                System.out.println("继承Thread类，重写run()方法");
                System.out.println("继承Thread类:" + Thread.currentThread());
            }
        };
        extendsThread.start();

        /**
         * 实现Runnable接口
         * 无返回结果
         * 支持线程池
         * 适用场景：推荐方式（复杂线程任务）
         */
        for (int i = 0; i < 10; i++) {
            Thread implementRunnable = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("实现Runnable接口，重写run()方法");
                    System.out.println("实现Runnable方法:" + Thread.currentThread());

                }
            });
            implementRunnable.start();
        }

        /**
         * 注意:下面写法是错误的，不能直接使用run()，直接使用就是简单的调用，并没有开启多线程
         * 正确的方法是上面那种情况，
         * Thread thread  = new Thread(new Runnable(){
         *    重写run方法
         * });
         * thread.start;  开启多线程
         */
//        for (int i = 0; i < 10; i++) {
//            Runnable runnable = new Runnable() {
//                @Override
//                public void run() {
//                    System.out.println("实现Runnable方法！！！");
//                    System.out.println("实现Runnable方法:"+Thread.currentThread());
//                }
//            };
//            runnable.run();
//        }

        /**
         * 实现Callable接口
         * 特点：需要返回结果的场景
         * 支持线程池
         */
        System.out.println("开始");
        long start = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        List<Future<Object>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            futures.add(executorService.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    System.out.println("实现了callable接口！！！");
                    Thread.sleep(4000);
                    System.out.println("实现了callable接口:" + Thread.currentThread());
                    return "返回结果";
                }
            }));
        }
        for (Future<Object> future : futures) {
            Object o = future.get();
            System.out.println(o);
        }
        executorService.shutdown();

        System.out.println("当前线程：" + Thread.currentThread());
        System.out.println("结束：用时【"+(System.currentTimeMillis()-start)+"】");
    }


}
